// stores/useUser.js 聊天记录相关
import { defineStore } from "pinia";
import { ref, computed, watchEffect } from "vue";
import { loginByWxCode } from "@/global/userApi";

const useUser = defineStore("useUser", () => {
  // 当前用户
  const user = ref(uni.getStorageSync("userObj") || {});
  const userDeviceSystem = ref(); //用户当前设备系统

  uni.getSystemInfo({
    success(res) {
      userDeviceSystem.value = res.osName;
    },
  });

  //微信静默登录
  const userLogin = (cb) => {
    uni.showLoading({
      title: "登录中...",
      mask: true,
    });
    uni.login({
      success(res) {
        loginByWxCode({ code: res.code }).then((res) => {
          if (res && res.code == 200) {
            user.value = res.data.userInfo;
            uni.setStorageSync("userObj", res.data.userInfo);
            uni.setStorageSync("currentUserId", res.data.userInfo.userId);
            setTimeout(() => {
              cb && cb();
              uni.hideLoading();
            }, 100);
          } else {
            uni.hideLoading();
          }
        });
      },
      fail(err) {
        console.log(err);
        uni.hideLoading();
      },
    });
  };

  return {
    user,
    userDeviceSystem,
    userLogin,
  };
});

export default useUser;
